package com.zoro.barn.commons.webcommons.response.components;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.zoro.barn.commons.webcommons.response.entity.BarnResponseEntity;
import com.zoro.barn.commons.webcommons.response.advice.ResponseDataAdvice;
import org.springframework.web.client.RestTemplate;

/**
 * 这个类用于将包装好的响应数据解包成，包装的结构请查看
 * {@link ResponseDataAdvice}和 {@link BarnResponseEntity}
 *
 * @author zhaoxingwu
 * @see ResponseDataAdvice
 * @see BarnResponseEntity
 */
public class RestTemplateUtil {

    private final RestTemplate restTemplate;

    public RestTemplateUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * send a post request ,return target Type's instance
     *
     * @param url    url
     * @param param  request body
     * @param tClass target type
     * @param <T>    type
     * @return response
     * @throws JsonProcessingException e
     */
    public <T> T postForEntity(String url, Object param, Class<T> tClass) throws JsonProcessingException {
        BarnResponseEntity<T> entity = restTemplate.postForEntity(url, param, BarnResponseEntity.class).getBody();
        return entity.getTargetData(tClass);
    }
}
